package com.example.springboot_springsecurity_jwt_redis.securityHandler;


import com.alibaba.fastjson.JSON;
import com.example.springboot_springsecurity_jwt_redis.common.Result;
import com.example.springboot_springsecurity_jwt_redis.common.ResultCodeEnum;
import com.example.springboot_springsecurity_jwt_redis.pojo.SelfUserDetails;
import com.example.springboot_springsecurity_jwt_redis.utils.AccessAddressUtil;
import com.example.springboot_springsecurity_jwt_redis.utils.JwtTokenUtil;
import com.example.springboot_springsecurity_jwt_redis.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录成功时返回给前端的数据
 */
@Component
@Slf4j
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    // 从application.yml 引入超时时间
    @Value("${token.expirationSeconds}")
    private int expirationSeconds;

    // 从application.yml 引人有效时间
    @Value("${token.validTime}")
    private int validTime;

    // 引入 RedistUtil 工具类
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获取请求的ip地址
        String ip = AccessAddressUtil.getIpAddress(httpServletRequest);
        // 将 ip 存在map中
        Map<String,Object> map = new HashMap<>();
        map.put("ip",ip);

        // 获得主体的身份
        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();

        // 传入实体名、超时时间、主体权限，获取token
        String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername(), expirationSeconds, map);

        //刷新时间
        Integer expire = validTime*24*60*60*1000;

        //获取请求的ip地址
        String currentIp = AccessAddressUtil.getIpAddress(httpServletRequest);

        //重新设置 token 的信息
        redisUtil.setTokenRefresh(jwtToken,userDetails.getUsername(),currentIp);

        // 打印用户已登录，和用户名
        log.info("用户{}登录成功，信息已保存至redis",userDetails.getUsername());

        // 返回值
        httpServletResponse.getWriter().write(JSON.toJSONString(Result.result(ResultCodeEnum.RESULT_CODE_USER_LOGIN_SUCCESS,jwtToken,true)));
    }
}
